package dshop.action.admin;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import appbase.jfinal.ext.ApiBaseController;
import appbase.jfinal.ext.ModelKit;
import appbase.jfinal.ext.RecordKit;
import appbase.utils.DateUtil;
import dshop.AppConst;
import dshop.interceptor.ApiAuthInterceptor;
import dshop.interceptor.ApiReadBodyParamInterceptor;
import dshop.model.Account;
import dshop.model.Area;
import dshop.model.Login;
import dshop.model.LoginHistory;
import dshop.model.commerce.Commerce;
import dshop.model.company.Company;
import dshop.model.member.MemberCompany;
import dshop.model.member.MemberGeneralInfo;
import dshop.model.member.MemberPermission;
import dshop.model.member.MemberVip;
import dshop.model.member.StoreCompany;
import dshop.model.member.SupperCompany;

/**
 * 会员管理
 */
@Before({ ApiReadBodyParamInterceptor.class, ApiAuthInterceptor.class })
public class MemberAction extends ApiBaseController {

	public void list() {
		String realName = getPara("realName", "").trim();
		String phone = getPara("phone", "").trim();
//		String address = getPara("address", "").trim();
		String inviteCode = getPara("inviteCode", "").trim();
		int isAll = getParaToInt("isAll", 0);
//		System.out.println("address："+address);

		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];

		Date startDate = getParaToDateTime("startDate", "yyyy-MM-dd");
		Date endDate = getParaToDateTime("endDate", "yyyy-MM-dd");
		String checkStatus = getPara("checkStatus", "").trim();

		String select = " select m.account_id, m.gender, concat(m.last_name, m.first_name) as realName, m.avatar, m.phone, m.update_date_time, "
				+ " IFNULL(v.level_1,0) level_1, DATE_FORMAT(mvd.level_1_start_date_time,'%Y-%m-%d') level_1_start_date_time, DATE_FORMAT(mvd.level_1_end_date_time,'%Y-%m-%d') level_1_end_date_time, "
				+ " IFNULL(v.level_2,0) level_2, DATE_FORMAT(mvd.level_2_start_date_time,'%Y-%m-%d') level_2_start_date_time, DATE_FORMAT(mvd.level_2_end_date_time,'%Y-%m-%d') level_2_end_date_time, "
				+ " IFNULL(v.level_3,0) level_3, DATE_FORMAT(mvd.level_3_start_date_time,'%Y-%m-%d') level_3_start_date_time, DATE_FORMAT(mvd.level_3_end_date_time,'%Y-%m-%d') level_3_end_date_time, "
				+ " IFNULL(v.level_4,0) level_4, DATE_FORMAT(mvd.level_4_start_date_time,'%Y-%m-%d') level_4_start_date_time, DATE_FORMAT(mvd.level_4_end_date_time,'%Y-%m-%d') level_4_end_date_time, "
				+ " IFNULL(v.level_5,0) level_5, DATE_FORMAT(mvd.level_5_start_date_time,'%Y-%m-%d') level_5_start_date_time, DATE_FORMAT(mvd.level_5_end_date_time,'%Y-%m-%d') level_5_end_date_time, "
				+ "a.register_date_time, a.status, a.check_status, a.check_exception_explain ";
		String from = " from member_general_info m  left join member_vip v on v.account_id = m.account_id "
				+ " left join member_vip_detail mvd on v.account_id = mvd.account_id "
				+ " left join account a on a.id = m.account_id ";
		String where;
		if(1 == isAll) {
			where = " where 1=1 ";
		}else {
			where = " where v.account_id is not NULL and v.level_1 = 1 ";
		}
		String orderBy = " ";

		List<Object> params = new ArrayList<Object>();
		if (!realName.isEmpty()) {
			where += " and concat(m.last_name, m.first_name) = ? ";
			params.add(realName);
		}
		if (!inviteCode.isEmpty()) {
			from += " left join sp_sale_proxy ssp on ssp.user_id = m.account_id ";
			where += " and ssp.code = ? ";
			params.add(inviteCode);
		}
		if (!phone.isEmpty()) {
			where += " and (m.phone = ? or a.phone = ?)";
			params.add(phone);
			params.add(phone);
		}
		if (startDate != null) {
			Calendar cal = DateUtil.setTimeToZero(startDate);
			where += " and  mvd.level_1_start_date_time >= ? ";
			params.add(cal.getTime());
		}
		if (endDate != null) {
			Calendar cal = DateUtil.setTimeToMax(endDate);
			where += " and mvd.level_1_start_date_time <= ? ";
			params.add(cal.getTime());
		}

		if (!checkStatus.isEmpty()) {
			where += " and a.check_status = ? ";
			params.add(checkStatus);
		}

		if (!columnOrder.isEmpty()) {
			orderBy += " order by " + columnProp + " " + columnOrder;
		} else {
			orderBy = " order by m.update_date_time desc ";
		}

		Page<Record> page = page(select, from + where + orderBy, params.toArray());
		List<Record> list = page.getList();

//		MemberVip.setVipInfoToRs(list, "account_id");
		MemberCompany.setCompanyIdToRs(list, "account_id");
		Company.setInfoToRs(list, "company_id");

		renderSuccess();
	}

	public void visitorList() {
		String realName = getPara("realName", "").trim();
		String phone = getPara("phone", "").trim();
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];
		Date startDate = getParaToDateTime("startDate", "yyyy-MM-dd");
		Date endDate = getParaToDateTime("endDate", "yyyy-MM-dd");
		String checkStatus = getPara("checkStatus", "").trim();
		String select = " select m.account_id, m.gender, concat(m.last_name, m.first_name) as realName, m.avatar, m.phone, m.update_date_time, "
				+ "a.register_date_time, a.status, a.check_status, a.check_exception_explain,  co.`name` companyName, co.address_detail companyAddress ";
		String from = " from member_general_info m  left join member_vip v on v.account_id = m.account_id "
				+ " LEFT JOIN account a on a.id = m.account_id "
				+ "	LEFT JOIN member_company mc on mc.account_id = m.account_id "
				+ "	LEFT JOIN company co on co.id = mc.company_id ";
		String where = " where (v.account_id is NULL or (v.level_1 = 0 AND v.level_2 = 0 and v.level_3 = 0 AND v.level_4 = 0)) ";
		String orderBy = " ";
		List<Object> params = new ArrayList<Object>();
		if (!realName.isEmpty()) {
			where += " and concat(m.last_name, m.first_name) = ? ";
			params.add(realName);
		}
		if (!phone.isEmpty()) {
			where += " and (m.phone = ? or a.phone = ?)";
			params.add(phone);
			params.add(phone);
		}
		if (startDate != null) {
			Calendar cal = DateUtil.setTimeToZero(startDate);
			where += " and  a.register_date_time >= ? ";
			params.add(cal.getTime());
		}
		if (endDate != null) {
			Calendar cal = DateUtil.setTimeToMax(endDate);
			where += " and a.register_date_time <= ? ";
			params.add(cal.getTime());
		}

		if (!checkStatus.isEmpty()) {
			where += " and a.check_status = ? ";
			params.add(checkStatus);
		}
		if (!columnOrder.isEmpty()) {
			orderBy += " order by " + columnProp + " " + columnOrder;
		} else {
			orderBy = " order by m.update_date_time desc ";
		}
		Page<Record> page = page(select, from + where + orderBy, params.toArray());

		renderSuccess();
	}

	public void detail() {
		int accountId = getParaToInt("accountId");

		MemberGeneralInfo member = MemberGeneralInfo.dao.findById(accountId);
		setAttr("member", member);

		Account account = Account.dao.findByIdLoadColumns(accountId,
				"register_date_time, check_status, check_exception_explain, check_date_time");
		ModelKit.putDateFormat(account, "check_date_time", "check_date_time_str", "yyyy-MM-dd HH:mm:ss");
		setAttr("account", account);

		MemberVip memberVip = MemberVip.dao.findById(accountId);
		if (memberVip == null) {
			memberVip = new MemberVip();
		}
		setAttr("memberVip", memberVip);

		Company company = null;
		Integer companyId = MemberCompany.getCompanyId(accountId);
		if (companyId != null) {
			company = Company.dao.findById(companyId);
			Area.setNameToM(company, "province_code, city_code, area_code", "province, city, area");
		} else {
			company = new Company();
		}
		setAttr("company", company);

		ModelKit.putDateFormat(memberVip, "start_date_time", "start_date_time_str", "yyyy-MM-dd HH:mm");
		ModelKit.putDateFormat(memberVip, "end_date_time", "end_date_time_str", "yyyy-MM-dd HH:mm");

		renderSuccess();
	}

	public void setSeal() {
		int accountId = getParaToInt("id");

		Account.setStatus(accountId, Account.STATUS_SEAL);

		// 强制退出登录
		List<Login> loginList = Login.listBy(accountId);
		if (loginList != null && !loginList.isEmpty()) {
			for (Login login : loginList) {
				String accessToken = login.getStr("access_token");
				int loginId = login.getInt("id");

				LoginHistory.setLogoutForceBy(accessToken, accountId);
				Login.deleteBy(loginId);
			}
		}

		renderSuccess("禁用成功");
	}

	public void setNormal() {
		int accountId = getParaToInt("id");

		Account.setStatus(accountId, Account.STATUS_NORMAL);

		renderSuccess("启用成功");
	}

	@Before(Tx.class)
	public void checkStatusPass() {
		int accountId = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_PASS;

		Account.setCheckStatus(accountId, checkStatus, remark);

//		int vipLevel = MemberVip.getLevelOf(accountId);
//		
//		MemberPermission memberPermission = new MemberPermission();
//		memberPermission.set("account_id", accountId);
//		
//		//修改权限
//		if (vipLevel >= MemberVip.level_1)
//		{
//			memberPermission.set("publish_job", "TRUE")
//			  				.set("publish_procurement", "TRUE");
//		}
//		if (vipLevel >= MemberVip.level_2)
//		{
//			memberPermission.set("create_commerce", "TRUE")
//			  				.set("create_activity", "TRUE");
//		}
//		if (vipLevel >= MemberVip.level_1)
//		{
//			memberPermission.update();
//		}

		renderSuccess("审核成功");
	}

	public void checkStatusFail() {
		int accountId = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_FAIL;

		Account.setCheckStatus(accountId, checkStatus, remark);

		// 修改权限
//		MemberPermission.setPermissionOnCheckFail(accountId);

		renderSuccess("审核失败");
	}

	public void superCompanyList() {
		String realName = getPara("realName", "").trim();
		String phone = getPara("phone", "").trim();
		String inviteCode = getPara("inviteCode", "").trim();
		Date startDate = getParaToDateTime("startDate", "yyyy-MM-dd");
		Date endDate = getParaToDateTime("endDate", "yyyy-MM-dd");
		String checkStatus = getPara("checkStatus", "").trim();
		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];
		String select = " select sc.id,m.account_id, m.gender, concat(m.last_name, m.first_name) as realName, m.avatar, m.phone, "
				+ " DATE_FORMAT(a.register_date_time,'%Y-%m-%d' ) register_date_time, sc.check_status, DATE_FORMAT(sc.date_time,'%Y-%m-%d' ) date_time ";
		String from = " from supper_company sc " + "left join account a on a.id = sc.account_id "
				+ "LEFT JOIN member_general_info m on m.account_id = sc.account_id ";
		String where = " where 1 = 1 ";
		String orderBy = " order by sc.date_time desc ";
		List<Object> params = new ArrayList<Object>();
		if (!realName.isEmpty()) {
			where += " and concat(m.last_name, m.first_name) = ? ";
			params.add(realName);
		}
		if (!inviteCode.isEmpty()) {
			from += " left join sp_sale_proxy ssp on ssp.user_id = m.account_id ";
			where += " and ssp.code = ? ";
			params.add(inviteCode);
		}
		if (!phone.isEmpty()) {
			where += " and m.phone = ? ";
			params.add(phone);
		}
		if (!checkStatus.isEmpty()) {
			where += " and sc.check_status = ? ";
			params.add(checkStatus);
		}
		if (startDate != null) {
			Calendar cal = DateUtil.setTimeToZero(startDate);
			where += " and sc.date_time >= ? ";
			params.add(cal.getTime());
		}
		if (endDate != null) {
			Calendar cal = DateUtil.setTimeToMax(endDate);
			where += " and sc.date_time <= ? ";
			params.add(cal.getTime());
		}
		if (!columnOrder.isEmpty()) {
			orderBy = " order by " + columnProp + " " + columnOrder;
		}
		page(select, from + where + orderBy, params.toArray());
		renderSuccess();
	}

	public void superCompanyCheckStatusPass() {
		int id = getParaToInt("id");
		String checkStatus = AppConst.CHECK_STATUS_PASS;
		SupperCompany.setCheckStatus(id, checkStatus);
		renderSuccess("审核成功");
	}

	public void superCompanyCheckStatusFail() {
		int id = getParaToInt("id");
		String checkStatus = AppConst.CHECK_STATUS_FAIL;
		SupperCompany.setCheckStatus(id, checkStatus);
		renderSuccess("审核失败");
	}

	public void storeList() {
		String phone = getPara("phone", "").trim();
		String name = getPara("name", "").trim();
		Date startDate = getParaToDateTime("startDate", "yyyy-MM-dd");
		Date endDate = getParaToDateTime("endDate", "yyyy-MM-dd");
		String checkStatus = getPara("checkStatus", "").trim();
		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];
		String select = " SELECT st.security_deposit,sc.* ,DATE_FORMAT(st.create_date_time,'%Y-%m-%d' ) create_date_time,"
				+ " mv.level_2,DATE_FORMAT(mvd.level_2_start_date_time,'%Y-%m-%d' ) level_2_start_date_time,DATE_FORMAT(mvd.level_2_end_date_time,'%Y-%m-%d' ) level_2_end_date_time ";
		String from = " FROM store st LEFT JOIN store_company sc on st.id = sc.store_id "
				+ " LEFT JOIN member_vip mv on st.admin_id = mv.account_id "
				+ " LEFT JOIN account ac on ac.id = st.admin_id "
				+ " LEFT JOIN member_vip_detail mvd on mvd.account_id = mv.account_id ";
		String where = " where 1 = 1 ";
		String orderBy = " order by sc.modified_time desc ";
		List<Object> params = new ArrayList<Object>();
		if (!phone.isEmpty()) {
			where += " and ac.phone = ? ";
			params.add(phone);
		}
		if (!name.isEmpty()) {
			where += " and sc.name like ? ";
			params.add(String.format("%%%s%%", name));
		}
		if (!checkStatus.isEmpty()) {
			where += " and sc.check_status = ? ";
			params.add(checkStatus);
		}
		if (startDate != null) {
			Calendar cal = DateUtil.setTimeToZero(startDate);
			where += " and mvd.level_2_start_date_time >= ? ";
			params.add(cal.getTime());
		}
		if (endDate != null) {
			Calendar cal = DateUtil.setTimeToMax(endDate);
			where += " and mvd.level_2_start_date_time <= ? ";
			params.add(cal.getTime());
		}
		if (!columnOrder.isEmpty()) {
			orderBy = " order by " + columnProp + " " + columnOrder;
		}
		page(select, from + where + orderBy, params.toArray());
		renderSuccess();
	}

	public void storeDetail() {
		int storeId = getParaToInt("storeId");
		List<Object> params = new ArrayList<Object>();
		params.add(storeId);
		Record store = Db.findFirst(
				"SELECT sc.store_id , sc.name ,st.security_deposit, sc.logo ,st.service_phone, sc.intro , sc.cover , sc.img , sc.company_honor , sc.business_photo , sc.proof_photo , sc.address_detail , sc.main , sc.check_status , sc.check_status_explain ,  "
						+ " DATE_FORMAT(st.create_date_time,'%Y-%m-%d' ) create_date_time ,"
						+ " DATE_FORMAT(sc.establish_date,'%Y-%m-%d' ) establish_date, "
						+ " DATE_FORMAT(sc.check_date_time,'%Y-%m-%d' ) check_date_time "
						+ "from store st LEFT JOIN store_company sc on st.id = sc.store_id where sc.store_id = ? ",
				params.toArray());
		store.set("cover", JSON.parseArray(store.getStr("cover"), String.class));
		store.set("img", JSON.parseArray(store.getStr("img"), String.class));
		store.set("company_honor", JSON.parseArray(store.getStr("company_honor"), String.class));
		store.set("business_photo", JSON.parseArray(store.getStr("business_photo"), String.class));
		store.set("proof_photo", JSON.parseArray(store.getStr("proof_photo"), String.class));
		setAttr("store", store);
		renderSuccess();
	}

	public void storeCheckStatusPass() {
		int id = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_PASS;
		StoreCompany.setCheckStatus(id, checkStatus, remark);
		renderSuccess("审核成功");
	}

	public void storeCheckStatusFail() {
		int id = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_FAIL;
		StoreCompany.setCheckStatus(id, checkStatus, remark);
		renderSuccess("审核失败");
	}

	public void commerceList() {
		String phone = getPara("phone", "").trim();
		String name = getPara("name", "").trim();
		Date startDate = getParaToDateTime("startDate", "yyyy-MM-dd");
		Date endDate = getParaToDateTime("endDate", "yyyy-MM-dd");
		// 排序
		String columnProp = getPara("columnProp", "").trim();
		String columnOrder = getPara("columnOrder", "").trim().split("ending")[0];
		String checkStatus = getPara("checkStatus", "").trim();
		String select = " SELECT sc.id ,sc.account_id ,sc.name ,sc.address ,sc.longitude ,sc.latitude ,sc.intro ,sc.logo ,sc.cover ,sc.type ,sc.img ,sc.address_detail ,sc.check_status ,sc.check_status_explain ,sc.modified_time, "
				+ " DATE_FORMAT(sc.create_date_time,'%Y-%m-%d' ) create_date_time,  "
				+ " DATE_FORMAT(sc.check_date_time,'%Y-%m-%d' ) check_date_time ," + " mv.level_3, "
				+ "	DATE_FORMAT(mvd.level_3_start_date_time,'%Y-%m-%d' ) level_3_start_date_time, "
				+ "	DATE_FORMAT(mvd.level_3_end_date_time,'%Y-%m-%d' ) level_3_end_date_time, " + "	mv.level_4, "
				+ "	DATE_FORMAT(mvd.level_4_start_date_time,'%Y-%m-%d' ) level_4_start_date_time, "
				+ "	DATE_FORMAT(mvd.level_4_end_date_time,'%Y-%m-%d' ) level_4_end_date_time ";
		String from = " FROM commerce sc " + " LEFT JOIN member_vip mv on mv.account_id = sc.account_id "
				+ " LEFT JOIN member_vip_detail mvd on mvd.account_id = sc.account_id "
				+ " LEFT JOIN account ac on ac.id = sc.account_id ";
		String where = " where 1 = 1 ";
		String orderBy = " order by sc.modified_time desc ";
		List<Object> params = new ArrayList<Object>();
		if (!phone.isEmpty()) {
			where += " and ac.phone = ? ";
			params.add(phone);
		}
		if (!name.isEmpty()) {
			where += " and sc.name like ? ";
			params.add(String.format("%%%s%%", name));
		}
		if (!checkStatus.isEmpty()) {
			where += " and sc.check_status = ? ";
			params.add(checkStatus);
		}
		if (startDate != null) {
			Calendar cal = DateUtil.setTimeToZero(startDate);
			where += " and (mvd.level_3_start_date_time >= ? or mvd.level_4_start_date_time >= ? )";
			params.add(cal.getTime());
			params.add(cal.getTime());
		}
		if (endDate != null) {
			Calendar cal = DateUtil.setTimeToMax(endDate);
			where += " and (mvd.level_4_end_date_time <= ? or mvd.level_4_end_date_time <= ? )";
			params.add(cal.getTime());
			params.add(cal.getTime());
		}
		if (!columnOrder.isEmpty()) {
			if ("open_time".equals(columnProp)) {
				orderBy = " order by level_3_start_date_time " + columnOrder+" ,level_4_start_date_time " + columnOrder;
			}else {
				orderBy = " order by " + columnProp + " " + columnOrder;
			}
		}
		page(select, from + where + orderBy, params.toArray());
		renderSuccess();
	}

	public void commerceDetail() {
		int id = getParaToInt("id");
		List<Object> params = new ArrayList<Object>();
		params.add(id);
		String select = " SELECT sc.id ,sc.account_id ,sc.name ,sc.address ,sc.longitude ,sc.latitude ,sc.intro ,sc.logo ,sc.cover ,sc.type ,sc.img ,sc.address_detail ,sc.check_status ,sc.check_status_explain ,"
				+ " DATE_FORMAT(sc.create_date_time,'%Y-%m-%d' ) create_date_time,  "
				+ " DATE_FORMAT(sc.check_date_time,'%Y-%m-%d' ) check_date_time FROM commerce sc where sc.id = ?  ";
		Record commerce = Db.findFirst(select, params.toArray());
		commerce.set("cover", JSON.parseArray(commerce.getStr("cover"), String.class));
		commerce.set("img", JSON.parseArray(commerce.getStr("img"), String.class));
		setAttr("commerce", commerce);
		renderSuccess();
	}

	public void commerceCheckStatusPass() {
		int id = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_PASS;
		Commerce.setCheckStatus(id, checkStatus, remark);
		renderSuccess("审核成功");
	}

	public void commerceCheckStatusFail() {
		int id = getParaToInt("id");
		String remark = getPara("remark", "").trim();
		String checkStatus = AppConst.CHECK_STATUS_FAIL;
		Commerce.setCheckStatus(id, checkStatus, remark);
		renderSuccess("审核失败");
	}
}
